package br.com.consigsys.controller;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.UploadedFile;

import br.com.consigsys.util.FacesUtil;
import br.com.consigsys.util.TextUtil;

@ManagedBean
@SessionScoped
public class UploadController implements Serializable{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -6056596247326044008L;
	private byte[] photo;
	private UploadedFile uploadedPhoto;

	/**
	 * @return the photo
	 */
	public byte[] getPhoto() {
		return photo;
	}

	/**
	 * @param photo the photo to set
	 */
	public void setPhoto(byte[] photo) {
		this.photo = photo;
	}
	
	public void photoUpload(FileUploadEvent event){
		System.out.println("upload...");
		this.uploadedPhoto = event.getFile();
		this.photo = this.uploadedPhoto.getContents();
		
		//System.out.println(this.uploadedPhoto.getFileName().contentType());
		FacesUtil.addInfoMessage(TextUtil.getMessage("success"), TextUtil.getMessage("successPhotoUpload"));

	}
	
	public StreamedContent getPhotoStream() {
		if (this.photo != null) {
			InputStream inputStream = new ByteArrayInputStream(this.photo);
			StreamedContent photo = new DefaultStreamedContent(inputStream);
			return photo;
		}
		return null;
	}
	
	public void clearUpload(){
		this.uploadedPhoto = null;
		this.photo = null;
	}

	/**
	 * @return the uploadedPhoto
	 */
	public UploadedFile getUploadedPhoto() {
		return uploadedPhoto;
	}

	/**
	 * @param uploadedPhoto the uploadedPhoto to set
	 */
	public void setUploadedPhoto(UploadedFile uploadedPhoto) {
		this.uploadedPhoto = uploadedPhoto;
	}
}
